package LeetCode;

import java.util.*;

/**
 * 输入: s = "abcabcbb"
 * 输出: 3
 * 解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3。
 */

public class MaxSubStr_leetcode3 {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
    }


    public static int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1) {
            return s.length();
        }
        char[] a = s.toCharArray();
        int max = 0;
        int cnt = 0;
        int index = 0;
        int pos = 1;
        List<Character> list = new ArrayList<>();
        HashSet<Character> set = new HashSet<>();
        set.add(a[index]);
        cnt = 1;
        while (index < a.length && pos < a.length) {
            boolean add = set.add(a[pos]);
            if (add) {
                cnt++;
                pos++;
            } else {
                for (int curIndex = index; curIndex < pos; curIndex++) {
                    if (a[pos] == a[curIndex]) {
                        index = curIndex + 1;
                        pos = index + 1;
                        break;
                    }
                }
                set.clear();
                set.add(a[index]);
                cnt = 1;
            }
            max = max > cnt ? max : cnt;
        }
        return max;
    }

}
